package com.gitee.wenbo0;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import static com.gitee.wenbo0.DictTextResultSetHandlerPlugin.CACHE_SQL;
import static com.gitee.wenbo0.DictTextResultSetHandlerPlugin.rsToList;

@Component
@Slf4j
public class ApplicationStartEventListener implements ApplicationListener<ApplicationStartedEvent> {


    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        DataSource dataSource = (DataSource) SpringContextHolder.getBean("dataSource");
        DictTextResultSetHandlerPlugin dictTextResultSetHandlerPlugin = SpringContextHolder.getBean(DictTextResultSetHandlerPlugin.class);
        new Thread(() -> {
            while (true) {
                try (Connection conn = dataSource.getConnection()) {
                    for (String tableName : dictTextResultSetHandlerPlugin.cacheTableNameList) {
                        List<Map<String, String>> cacheList = dictTextResultSetHandlerPlugin.timedCache.get(tableName.toLowerCase(), false);
                        if (cacheList == null) {
                            try (ResultSet rs = conn.prepareStatement(String.format(CACHE_SQL, tableName)).executeQuery()) {
                                List<Map<String, String>> list = rsToList(rs);
                                dictTextResultSetHandlerPlugin.timedCache.put(tableName.toLowerCase(), list);
                            }
                        }
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                log.debug("更新缓存数据成功");
                try {
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        log.info("mybatis-plus-wrapper---->加载缓存成功");
    }
}
